//
//  UIViewController+Loading.m
//  
//
//  Created by Charles on 16/5/15.
//  Copyright © 2016年 Com.Charles. All rights reserved.
//

#import "UIViewController+Loading.h"
#import <objc/message.h>

const static char loadingViewKey;

@interface UIViewControllerLodingView : UIView
@property (nonatomic, weak) UIActivityIndicatorView *indicatorView;
@property(nonatomic,weak) UILabel * load;
@end

@implementation UIViewControllerLodingView

- (UIActivityIndicatorView *)indicatorView {
    if (!_indicatorView) {
        UIActivityIndicatorView *indicatorView = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
        [self addSubview:indicatorView];
        _indicatorView = indicatorView;
    }
    return _indicatorView;
}

- (UILabel *)load
{
    if (!_load) {
        UILabel *load = [[UILabel alloc] init];
        load.text = @"正在加载中...";
        load.textColor = [UIColor grayColor];
        load.font = FONT(12);
        _load = load;
        [self addSubview:load];
    }
    return _load;
}

- (void)startAnimating {
    [self.indicatorView startAnimating];
}

- (void)layoutSubviews {
    [super layoutSubviews];
    self.indicatorView.center = self.center;
    [self.load mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.indicatorView.mas_bottom).offset(3);
        make.centerX.equalTo(self);
    }];
}

@end

@implementation UIViewController (Loading)

- (void)showLoadingView {
    [self showLoadingViewWithFrame:CGRectMake(0, 0,WIDTH,HEIGHT)];
}

- (UIView *)loadingView {
    return objc_getAssociatedObject(self, &loadingViewKey);
}

- (void)setLoadingView:(UIView *)loadingView {
    objc_setAssociatedObject(self, &loadingViewKey, loadingView,
                             OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}

- (void)showLoadingViewWithFrame:(CGRect)frame {
    if (!self.loadingView) {
        UIViewControllerLodingView *loadingView = [[UIViewControllerLodingView alloc]
                                                init];
        self.loadingView = loadingView;
        loadingView.frame = frame;
        [self.view addSubview:self.loadingView];
        loadingView.center = self.view.center;
        loadingView.centerY = self.view.centerY - 50;
        [loadingView startAnimating];
    }
}

- (void)hideLoadingView {
    if (self.loadingView) {
        [self.loadingView removeFromSuperview];
        objc_removeAssociatedObjects(self);
    }
}
@end
